package com.zhang.zhangapp.base.http;

import com.zhang.zhangapp.application.MApplication;
import com.zhang.zhangapp.utils.T;

import org.json.JSONObject;

/**
 * Created by 罗肖 on 2017/6/30.
 */
public class CommonCallBack implements org.xutils.common.Callback.CommonCallback<String> {

    private MCallback callback;

    public CommonCallBack(MCallback callback) {
        this.callback = callback;
    }

    @Override
    public void onSuccess(String result) {
//        T.showShort(MApplication.getInstance().getApplicationContext(),result);
        try {
            JSONObject jsonObject = new JSONObject(result);
            String code = jsonObject.get("code").toString();
            String message = "请求失败";
            if (jsonObject.has("message") && jsonObject.get("message") != null)
                message = jsonObject.get("message").toString();
            if ("0".equals(code)) {//请求成功 且有数据
                callback.onSuccess(jsonObject.has("data")?jsonObject.get("data").toString():"");
            } else {
                callback.onSuccess(message, code);
            }
        } catch (Exception e) {
            Throwable ex = new Throwable(e.getMessage());
            callback.onError(ex, false);
        }
    }

    @Override
    public void onError(Throwable ex, boolean isOnCallback) {
        callback.onError(ex, isOnCallback);
    }

    @Override
    public void onCancelled(CancelledException cex) {
        callback.onCancelled(cex);
    }

    @Override
    public void onFinished() {
        callback.onFinished();
    }
}
